package cn.com.ustudy.course.core.web.ctrl;

import cn.com.ustudy.course.core.comp.service.CourseService;
import cn.melonlib.cores.commons.comp.web.ctrl.BasicController;
import cn.melonlib.cores.jpa.model.bean.collections.JsonMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

@RestController
@RequestMapping("/course")
public class CourseController extends BasicController {

    @Value("${resource.web.store.upload:/service/resources/upload}")
    private String uploadRootPath;

    @Resource
    private CourseService courseService;
    @PostMapping(value = "/logo/upload.api",produces = {BasicController.APPLICATION_JSON_UTF8_VALUE})
    public String uploadLogo(
            MultipartHttpServletRequest request
    ) throws Exception{
        MultipartFile logo=request.getFile("file");
        String courseId=request.getParameter("courseId");
        courseService.saveLogo(logo,courseId);
        return JsonMap.createMap().append("status",true).jsonString();
    }

    @GetMapping(path = "/logo/**")
    public void logo(
            HttpServletRequest request, HttpServletResponse response
            ) throws Exception{
        String path=request.getServletPath();
        path=path.replace("/course/logo",uploadRootPath);
        File logo=new File(path);
        this.downloadConfig(request,response,logo.getName(),logo.length(),"image/*");
        try(InputStream in=new FileInputStream(logo); OutputStream out=response.getOutputStream()){
            StreamUtils.copy(in,out);
        }
    }
}
